package com.witmore.neutron.ai.web.apiv2.nls;//package com.witmore.neutron.ai.web.tts;

import com.alibaba.nls.client.protocol.InputFormatEnum;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.asr.SpeechRecognizer;
import com.alibaba.nls.client.protocol.asr.SpeechRecognizerListener;
import com.alibaba.nls.client.protocol.asr.SpeechRecognizerResponse;
import com.witmore.neutron.ai.web.apiv2.nls.config.NlsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;

/**
 * ASR一句话识别API调用
 * 通过本地文件模拟实时流发送
 * 识别耗时计算
 */

@Service
@Slf4j
public class SpeechRecognizerClient {
    @Autowired
    private NlsClient client;

    @Autowired
    private NlsProperties nlsProperties;

    public SpeechRecognizerClient(NlsClient client, NlsProperties nlsProperties) {
        this.client = client;
        this.nlsProperties = nlsProperties;
    }

    // 传入自定义参数
    private static SpeechRecognizerListener getRecognizerListener(int myOrder, String userParam) {
        SpeechRecognizerListener listener = new SpeechRecognizerListener() {
            //识别出中间结果.服务端识别出一个字或词时会返回此消息.仅当setEnableIntermediateResult(true)时,才会有此类消息返回
            @Override
            public void onRecognitionResultChanged(SpeechRecognizerResponse response) {
                //事件名称 RecognitionResultChanged、 状态码(20000000 表示识别成功)、语音识别文本
                log.info("name: {}, status: {}, result: {}", response.getName(), response.getStatus(), response.getRecognizedText());
            }

            //识别完毕
            @Override
            public void onRecognitionCompleted(SpeechRecognizerResponse response) {
                //事件名称 RecognitionCompleted, 状态码 20000000 表示识别成功, getRecognizedText是识别结果文本
                log.info("name: {}, status: {}, result: {}", response.getName(), response.getStatus(), response.getRecognizedText());
            }

            @Override
            public void onStarted(SpeechRecognizerResponse response) {
                log.info("myOrder: {}, myParam: {}, task_id: {}", myOrder, userParam, response.getTaskId());
            }

            @Override
            public void onFail(SpeechRecognizerResponse response) {
                // TODO 重要提示： task_id很重要，是调用方和服务端通信的唯一ID标识，当遇到问题时，需要提供此task_id以便排查
                log.info("task_id: {}, status: {}, status_text: {}", response.getTaskId(), response.getStatus(), response.getStatusText());
            }
        };
        return listener;
    }

    /// 根据二进制数据大小计算对应的同等语音长度
    /// sampleRate 仅支持8000或16000
    public static int getSleepDelta(int dataSize, int sampleRate) {
        // 仅支持16位采样
        int sampleBytes = 16;
        // 仅支持单通道
        int soundChannel = 1;
        return (dataSize * 10 * 8000) / (160 * sampleRate);
    }

    public void process(String filepath, int sampleRate) {
        SpeechRecognizer recognizer = null;
        try {
            // 传递用户自定义参数
            String myParam = "user-param";
            int myOrder = 1234;
            SpeechRecognizerListener listener = getRecognizerListener(myOrder, myParam);

            recognizer = new SpeechRecognizer(client, listener);
            recognizer.setAppKey(nlsProperties.getAppKey());

            //设置音频编码格式 TODO 如果是opus文件，请设置为 InputFormatEnum.OPUS
            recognizer.setFormat(InputFormatEnum.PCM);
            //设置音频采样率
            if (sampleRate == 16000) {
                recognizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
            } else if (sampleRate == 8000) {
                recognizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_8K);
            }
            //设置是否返回中间识别结果
            recognizer.setEnableIntermediateResult(true);

            //此方法将以上参数设置序列化为json发送给服务端,并等待服务端确认
            long now = System.currentTimeMillis();
            recognizer.start();
            log.info("ASR start latency : {} ms", System.currentTimeMillis() - now);

            ClassPathResource classPathResource = new ClassPathResource(filepath);
            File file = classPathResource.getFile();
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[3200];
            int len;
            while ((len = fis.read(b)) > 0) {
                log.info("send data pack length: {}", len);
                recognizer.send(b, len);

                // TODO  重要提示：这里是用读取本地文件的形式模拟实时获取语音流并发送的，因为read很快，所以这里需要sleep
                // TODO  如果是真正的实时获取语音，则无需sleep, 如果是8k采样率语音，第二个参数改为8000
                // 8000采样率情况下，3200byte字节建议 sleep 200ms，16000采样率情况下，3200byte字节建议 sleep 100ms
                int deltaSleep = getSleepDelta(len, sampleRate);
                Thread.sleep(deltaSleep);
            }

            //通知服务端语音数据发送完毕,等待服务端处理完成
            now = System.currentTimeMillis();

            // TODO 计算实际延迟: stop返回之后一般即是识别结果返回时间
            log.info("ASR wait for complete");
            recognizer.stop();
            log.info("ASR stop latency : {} ms", System.currentTimeMillis() - now);

            fis.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            //关闭连接
            if (null != recognizer) {
                recognizer.close();
            }
        }
    }

    public void shutdown() {
        client.shutdown();
    }





    /**
     * 默认凭证过期时间 单位：秒
     */
    private static final long EXPIRE_TIME_SECOND = 3600 * 24;

    /**
     * 获取 上传下载凭证
     */
//    public Map<String, String> getCredentials(Long expireTime) throws Exception {
//        Map<String, String> responseMap = new HashMap<>();
//        try {
//            if (expireTime == null) {
//                expireTime = EXPIRE_TIME_SECOND;
//            }
//            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
//            Date expiration = new Date(expireEndTime);
//
//
//            PolicyConditions policyConds = new PolicyConditions();
//            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
//            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prefix);
//            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
//            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
//            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
//            String postSignature = ossClient.calculatePostSignature(postPolicy);
//            responseMap.put("ossAccessKeyId", ossProperties.getRamAccessKeyId());
//            responseMap.put("policy", encodedPolicy);
//            responseMap.put("signature", postSignature);
//            responseMap.put("dir", prefix);
//            responseMap.put("host", ossProperties.getUrl());
//            responseMap.put("expire", String.valueOf(expireTime));
//            // 日期格式转换
//
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String formattedDate = sdf.format(expiration);
//            responseMap.put("expireDate", formattedDate);
//
//        } catch (OSSException | ClientException oe) {
//            throw new Exception(oe);
//        }
//        return responseMap;
//    }
}
